<?php
namespace app\admin\util;
use think\facade\Cache;

class Aes
{
    private $hex_iv = 'q3YFUCScYiXCDqSie3NLDjMQQcJSmETa';
    private $key = 'NYNhWRWDhQ97lWpVKrU2e1bHI42e8Dcw';
    private $redis;

    function __construct($key = '')
    {
        $this->key = $key ?: $this->key;
        $this->key = hash('sha256', $this->key, true);
        $this->redis = Cache::store('redis');
    }

    //获取token
    public function getToken($encrypted, $type = 'admin')
    {
        $users = json_decode($this->decrypt($encrypted), true);
        $userTokenArr = $users ? $this->redis->hGetAll("user_{$type}:{$users['uid']}") : [];
        return !empty($userTokenArr) && $userTokenArr['token'] == $encrypted ? $users : [];
    }

    //生成token
    public function setToken($uid, $type = 'admin')
    {
        $expires_in = 60 * 60 * 24 * 60;  //有效期：60天
        $token = $this->encrypt(json_encode(["uid" => $uid, "expires_in" => $expires_in, "login_time" => time()]));

        $tokenArr = ["uid" => $uid,"expire" => $expires_in, "token" => $token];

        $key = "user_{$type}:{$uid}";

        $this->redis->hMSet($key, $tokenArr);
        $this->redis->expire($key, $expires_in);

        return !empty($this->getToken($token, $type)) ? $token : '';
    }

    //删除token
    public function rmToken($encrypted, $type = 'admin')
    {
        $users = json_decode($this->decrypt($encrypted), true);
        $key = "user_{$type}:{$users['uid']}";
        return $this->redis->del($key);
    }

    //AES加密
    public function encrypt($input)
    {
        $data = openssl_encrypt($input, 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->hexToStr($this->hex_iv));
        $data = base64_encode($data);
        return $data;
    }

    //AES解密
    public function decrypt($input)
    {
        $decrypted = openssl_decrypt(base64_decode($input), 'AES-256-CBC', $this->key, OPENSSL_RAW_DATA, $this->hexToStr($this->hex_iv));
        return $decrypted;
    }

    function hexToStr($hex)
    {
        $string = '';
        for ($i = 0; $i < strlen($hex) - 1; $i += 2) {
            $string .= chr(hexdec($hex[$i] . $hex[$i + 1]));
        }
        return $string;
    }
}

